import React, { useState } from 'react';
import './register.css';
import { Input, Button } from '@nutui/nutui-react';
import { useNavigate } from 'react-router-dom';
import axios from "../../axios";

export default function Register() {
    const navigate = useNavigate();
    const [user, setUser] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);


    const handleSubmit = async (event) => {
        event.preventDefault();
        setLoading(true);
        setError('');

        try {
            const formData = {
                user,
                password
            };

            const response = await axios.post('/register', formData);

            if (response.data.code == 200) {
                navigate('/login');
            } else {
                setError(response.data.message || '注册失败');
            }
        } catch (error) {
            setError('请重试');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="register">
            <div className="wel1">
                <h2>欢迎来到优尼</h2>
            </div>
            <div className="input">
                <div className="input1">
                    <h4>账号</h4>
                    <Input
                        type="text"
                        placeholder="手机/用户名/邮箱"
                        value={user}
                        onChange={(value) => setUser(value)}
                    />
                </div>
                <div className="input2">
                    <h4>密码</h4>
                    <Input
                        type="password"
                        placeholder="输入你的密码"
                        value={password}
                        onChange={(value) => setPassword(value)}
                    />
                </div>
            </div>
            <div className="welbtu">
                <div className="welbtu1">
                    <Button
                        htmlType="submit"
                        onClick={handleSubmit}
                        loading={loading}
                    >
                        {loading ? '注册中...' : '立即注册'}
                    </Button>
                </div>
                <div className="welbtu2">
                    <Button onClick={() => navigate('/login')}>
                        暂不注册
                    </Button>
                </div>
            </div>
            {error && <p className="error-message">{error}</p>}
        </div>
    );
}